package com.twt.config.mybatis;

import com.twt.common.utils.SpringContextUtil;
import com.twt.config.mybatis.surppot.DataSourceBuildFactory;
import com.twt.config.mybatis.surppot.DataSourceBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Desciption:
 * @ClassName:DataSourceRegListener
 * @Author:TwT
 * @Date:2022/6/3 10:17
 * @Version:1.0
 **/
@Slf4j
//@Component
public class DataSourceRegListener implements ApplicationRunner {

    @Autowired
    private DataSourceListCfgProperties dsCfgProperties;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) SpringContextUtil.getSpringContext();
        BeanDefinitionRegistry beanDefinitionRegistry = (BeanDefinitionRegistry) configurableApplicationContext.getBeanFactory();


        Map<String, MybatisDataSourceProperty> dataSourceList = dsCfgProperties.getDataSourceList();
        dataSourceList.keySet().stream().forEach(sourceName->{
            log.debug("数据源：{}",sourceName);
            this.registryBean(beanDefinitionRegistry,dataSourceList.get(sourceName),sourceName);
        });
    }

    private void registryBean(BeanDefinitionRegistry registry,MybatisDataSourceProperty dataSourceProperty,String beanName) {
        String datasourceType = dataSourceProperty.getDatasourceType();

        DataSourceBuildFactory dataSourceBuildFactory = new DataSourceBuildFactory();
        DataSourceBuilder dataSourceBuilder = dataSourceBuildFactory.getDataSourceBuilder(datasourceType);
        dataSourceBuilder.setBeanDefinitionRegistry(registry);
        dataSourceBuilder.setBeanName(beanName);
        dataSourceBuilder.setMybatisDataSourceProperty(dataSourceProperty);

        dataSourceBuilder.registry();
    }

}
